package com.xh.bussiness.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.system.bean.dto.GradeRangeDto;
import com.xh.bussiness.system.bean.dto.GroupDetailBean;
import com.xh.bussiness.system.bean.request.GroupRequest;
import com.xh.bussiness.system.constant.UserDataCacheConstant;
import com.xh.bussiness.system.dao.GroupMapper;
import com.xh.bussiness.system.model.*;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.service.*;
import com.xh.bussiness.tiku.model.BookVersion;
import com.xh.bussiness.tiku.service.IBookVersionService;
import com.xh.core.bean.XhPage;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.CacheUtils;
import com.xh.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户组 服务实现类
 * </p>
 *
 * @author Pitt
 * @since 2020-11-23
 */
@Service
public class GroupServiceImpl extends BaseServiceImpl<GroupMapper, Group> implements IGroupService {

    @Autowired
    private IGroupSubjectService groupSubjectService;
    @Autowired
    private IGroupRuleService groupRuleService;
    @Autowired
    private IGroupUserService groupUserService;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private IBookVersionService bookVersionService;
    @Autowired
    private ICourseSystemService courseSystemService;

    @Override
    public XhPage queryGroupPage(XhPage page, GroupRequest bean) {
        return this.dao.selectGroupList(page, bean);
    }

    @Override
    public List queryGroup(GroupRequest bean) {
        List<Group> groups = this.dao.selectGroupList(bean);
        if (CollectionUtils.isEmpty(groups)) {
            return new ArrayList();
        }
        if (!CollectionUtils.isEmpty(groups)) {
            return groups.stream().sorted(Comparator.comparing(Group::getSortIndex)).collect(Collectors.toList());
        }
        return new ArrayList();
    }

    @Override
    public boolean saveOrUpdateGroup(Group group) {
        //获取所有学科toMap
        Map<String, String> subjectMap = dictionaryService.queryDictByTypeCodes(Arrays.asList("SUBJECT")).stream().collect(Collectors.toMap((item -> item.getCode()), item -> item.getName(), (a, b) -> a));
        if (StringUtils.isEmpty(group.getId())) {
            Integer sortIndex = this.dao.selectMaxSortIndex();
            group.setSortIndex(sortIndex == null ? 1 : sortIndex + 1);
            this.insert(group);

            for (GroupSubject groupSubject : group.getGroupSubjects()) {
                String subjectCode = groupSubject.getSubjectCode();
                Dictionary gradeRange = dictionaryService.queryGradeRangeBySubjectCode(subjectCode);
                if (gradeRange != null) {
                    groupSubject.setSubjectName(subjectMap.get(subjectCode));
                    groupSubject.setGroupId(group.getId());
                    groupSubject.setGradeRangeId(gradeRange.getCode());
                    groupSubject.setGradeRangeName(gradeRange.getName());
                }
                groupSubjectService.insert(groupSubject);
            }
        } else {
            this.update(group);
            //结果临时查询出来
            List<GroupRule> tempGroupRules = groupRuleService.queryGroupRuleByGroupId(group.getId(), null);
            //清空与组相关数据
            groupSubjectService.deleteGroupSubjectByGroupId(group.getId());
            groupRuleService.deleteByGroupId(group.getId(), null);

            for (GroupSubject groupSubject : group.getGroupSubjects()) {
                Dictionary gradeRange = dictionaryService.queryGradeRangeBySubjectCode(groupSubject.getSubjectCode());
                if (gradeRange != null) {
                    groupSubject.setGroupId(group.getId());
                    groupSubject.setSubjectName(subjectMap.get(groupSubject.getSubjectCode()));
                    groupSubject.setGradeRangeId(gradeRange.getCode());
                    groupSubject.setGradeRangeName(gradeRange.getName());
                }
                groupSubjectService.insert(groupSubject);
                //查询该组对应学科是否配置过权限
                if (!CollectionUtils.isEmpty(tempGroupRules)) {
                    List<GroupRule> groupRules = tempGroupRules.stream().filter(item -> item.getSubjectCode().equals(groupSubject.getSubjectCode())).collect(Collectors.toList());
                    groupRuleService.batchInsert(groupRules);
                }
            }
        }
        CacheUtils.delete(UserDataCacheConstant.GROUP_DATA_VERSIN_KEY);
        return true;
    }

    @Override
    public boolean configGroupRule(Group group) {
        groupRuleService.deleteByGroupId(group.getId(),null);
        if (!CollectionUtils.isEmpty(group.getGroupRules())) {
            for (GroupRule groupRule : group.getGroupRules()) {
                groupRule.setGroupId(group.getId());
            }
            groupRuleService.batchInsert(group.getGroupRules());
        }
        CacheUtils.delete(UserDataCacheConstant.GROUP_DATA_VERSIN_KEY);
        return true;
    }

    @Override
    public GroupDetailBean queryGroupDetailByGroupId(String groupId) {
        Group group = this.getById(groupId);
        if (group == null) {
            throw new XhException("用户组不存在");
        }
        List<GroupSubject> groupSubjects = groupSubjectService.queryGroupSubjectByGroupId(groupId);
        if (CollectionUtils.isEmpty(groupSubjects)) {
            throw new XhException("用户组学科获取失败");
        }
        for (GroupSubject groupSubject : groupSubjects) {
            //所有年份
            List<Dictionary> years = dictionaryService.queryDictByTypeCodes(Arrays.asList("YEAR"));
            //所有年级
            List<Dictionary> grades = courseSystemService.queryDictionaryByCourseSystem(groupSubject.getSubjectCode(), "GRADE");
            //所有学期
            List<Dictionary> semesters = courseSystemService.queryDictionaryByCourseSystem(groupSubject.getSubjectCode(), "SEMESTER");
            //所有课程分类
            List<Dictionary> courseTypes = courseSystemService.queryDictionaryByCourseSystem(groupSubject.getSubjectCode(), "COURSE_TYPE");
            //教材版本
            List<Dictionary> bookVersions = courseSystemService.queryDictionaryByCourseSystem(groupSubject.getSubjectCode(), "TEACH_BOOK_VERSION");

            List<GroupRule> groupRules = groupRuleService.queryGroupRuleByGroupId(groupId, groupSubject.getSubjectCode());
            if (!CollectionUtils.isEmpty(groupRules)) {
                GroupRule groupRule = groupRules.get(0);
                groupSubject.setLabelCount(getLabelCount(groupRule));
                //对应年份
                String yearStr = groupRule.getYear();
                if (!StringUtils.isEmpty(yearStr)) {
                    List<String> yearList = Arrays.asList(yearStr.split(","));
                    if(yearList.contains("0")){
                        //如果为零 则全部权限都选
                        years.stream().forEach(item -> item.setCheck(true));
                        Dictionary dictionary = new Dictionary();
                        dictionary.setName("全部");
                        dictionary.setCheck(true);
                        years.add(dictionary);
                    }else {
                        for (String year : yearList) {
                            years.stream().filter(item -> item.getId().equals(year)).forEach(item -> item.setCheck(true));
                        }
                    }
                }
                //对应年级
                String gradeIdStr = groupRule.getGradeId();
                if (!StringUtils.isEmpty(gradeIdStr) && !CollectionUtils.isEmpty(grades)) {
                    List<String> gradeList = Arrays.asList(gradeIdStr.split(","));
                    if(gradeList.contains("0")){
                        grades.stream().forEach(item -> item.setCheck(true));
                        Dictionary dictionary = new Dictionary();
                        dictionary.setName("全部");
                        dictionary.setCheck(true);
                        grades.add(dictionary);
                    }else {
                        for (String grade : gradeList) {
                            grades.stream().filter(item -> item.getId().equals(grade)).forEach(item -> item.setCheck(true));
                        }
                    }
                }
                //对应学期
                String termIdStr = groupRule.getTermId();
                if (!StringUtils.isEmpty(termIdStr) && !CollectionUtils.isEmpty(semesters)) {
                    List<String> termIdList = Arrays.asList(termIdStr.split(","));
                    if(termIdList.contains("0")){
                        semesters.stream().forEach(item -> item.setCheck(true));
                        Dictionary dictionary = new Dictionary();
                        dictionary.setName("全部");
                        dictionary.setCheck(true);
                        semesters.add(dictionary);
                    }else{
                        for (String term : termIdList) {
                            semesters.stream().filter(item -> item.getId().equals(term)).forEach(item -> item.setCheck(true));
                        }
                    }
                }
                //对应课程分类
                String courseTypeStr = groupRule.getCourseTypeId();
                if (!StringUtils.isEmpty(courseTypeStr) && !CollectionUtils.isEmpty(courseTypes)) {
                    List<String> courseTypeList= Arrays.asList(courseTypeStr.split(","));
                    if(courseTypeList.contains("0")){
                        courseTypes.stream().forEach(item -> item.setCheck(true));
                        Dictionary dictionary = new Dictionary();
                        dictionary.setName("全部");
                        dictionary.setCheck(true);
                        courseTypes.add(dictionary);
                    }else {
                        for (String courseType : courseTypeList) {
                            courseTypes.stream().filter(item -> item.getId().equals(courseType)).forEach(item -> item.setCheck(true));
                        }
                    }
                }
                //对应教材
                String bookVersionIdStr = groupRule.getBookVersionId();
                if (!StringUtils.isEmpty(bookVersionIdStr) && !CollectionUtils.isEmpty(bookVersions)) {
                    List<String> bookVersionIdList = Arrays.asList(bookVersionIdStr.split(","));
                    if(bookVersionIdList.contains("0")){
                        bookVersions.stream().forEach(item -> item.setCheck(true));
                        Dictionary dictionary = new Dictionary();
                        dictionary.setName("全部");
                        dictionary.setCheck(true);
                        bookVersions.add(dictionary);
                    }else {
                        for (String bookVersionId : bookVersionIdList) {
                            //配置过该项设置选中
                            bookVersions.stream().filter(item -> item.getId().equals(bookVersionId)).forEach(item -> item.setCheck(true));
                        }
                    }
                }
            }
            //学科下的数据权限
            groupSubject.setYears(years);
            groupSubject.setGrades(grades);
            groupSubject.setSemester(semesters);
            groupSubject.setCourseTypes(courseTypes);
            groupSubject.setBookVersions(bookVersions);
        }

        //组装学科所属学段数据
        List<GradeRangeDto> gradeRangeDtos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(groupSubjects)) {
            //涉及排序，查一下
            List<String> gradeRangeIds = groupSubjects.stream().map(item -> item.getGradeRangeId()).distinct().collect(Collectors.toList());
            List<Dictionary> gradeRanges = dictionaryService.queryDictByCodes(gradeRangeIds);
            for (Dictionary gradeRange : gradeRanges) {
                GradeRangeDto gradeRangeDto = new GradeRangeDto();
                gradeRangeDto.setGradeRangeCode(gradeRange.getCode());
                gradeRangeDto.setGradeRangeName(gradeRange.getName());

                List<GroupSubject> gradeRangeSubjects = groupSubjects.stream().filter(item -> item.getGradeRangeId().equals(gradeRange.getCode())).collect(Collectors.toList());
                gradeRangeDto.setGroupSubjects(gradeRangeSubjects);

                gradeRangeDtos.add(gradeRangeDto);
            }
        }
        //返回数据
        GroupDetailBean detailBean = new GroupDetailBean();
        detailBean.setGroup(group);
        detailBean.setGradeRanges(gradeRangeDtos);
        return detailBean;
    }

    @Override
    public List<Group> queryUserGroupByUserId(String userId) {
        List<Group> allGroups = this.queryAll();
        List<GroupUser> groupUsers = groupUserService.queryGroupUserByUserId(userId);
        for (GroupUser groupUser : groupUsers) {
            allGroups.stream().filter(item -> item.getId().equals(groupUser.getGroupId())).forEach(item -> item.setCheck(true));
        }
        return allGroups;
    }

    @Override
    public Group queryGroupById(String groupId) {
        Group group = this.getById(groupId);
        if (group != null) {
            List<GroupSubject> groupSubjects = groupSubjectService.queryGroupSubjectByGroupId(groupId);
            if (!CollectionUtils.isEmpty(groupSubjects)) {
                group.setGroupSubjects(groupSubjects);
            }
        }
        return group;
    }


    @Override
    public List<Group> queryGroupByUserId(String userId) {
        List<Group> allGroups = groupUserService.queryGroupByUserId(userId);
        return allGroups;
    }

    @Override
    public boolean delete(Serializable id) {
        boolean result = super.delete(id);
        CacheUtils.delete(UserDataCacheConstant.GROUP_DATA_VERSIN_KEY);
        return result;
    }

    @Override
    public boolean batchDelete(Serializable[] ids) {
        boolean result = super.batchDelete(ids);
        CacheUtils.delete(UserDataCacheConstant.GROUP_DATA_VERSIN_KEY);
        return result;
    }

    /**
     * 获取数据权限数量
     *
     * @param groupRule
     * @return
     */
    private Integer getLabelCount(GroupRule groupRule) {
        Integer yearCount = StringUtils.isEmpty(groupRule.getYear()) ? 0 : groupRule.getYear().split(",").length;
        Integer gradeCount = StringUtils.isEmpty(groupRule.getGradeId()) ? 0 : groupRule.getGradeId().split(",").length;
        Integer termCount = StringUtils.isEmpty(groupRule.getTermId()) ? 0 : groupRule.getTermId().split(",").length;
        Integer bookVersionCount = StringUtils.isEmpty(groupRule.getBookVersionId()) ? 0 : groupRule.getBookVersionId().split(",").length;
        Integer courseTypeCount = StringUtils.isEmpty(groupRule.getCourseTypeId()) ? 0 : groupRule.getCourseTypeId().split(",").length;

        return yearCount + gradeCount + termCount + bookVersionCount + courseTypeCount;
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(GroupRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getGroupName())) {
            qw.like("name", bean.getGroupName());
        }

        return qw;
    }
}
